package com.qf.fmall.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.fmall.utils.JWTUtils;
import com.qf.fmall.vo.ResStatus;
import com.qf.fmall.vo.ResultVo;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String method = request.getMethod();
        if ("OPTIONS".equalsIgnoreCase(method)) {
            return true;
        }

        String token = request.getHeader("token"); //  从请求头中取token
        System.out.println(token);
        if ((token == null)) {
            ResultVo resultVo = new ResultVo(ResStatus.NO, "请先登录", null);
            doResponse(resultVo, response);
            return false;
        }
        if (JWTUtils.parseToken(token, "qf6666")) {
            System.out.println("成功");
            return true;
        } else {
            ResultVo resultVo = new ResultVo(ResStatus.NO, "请先登录", null);
            doResponse(resultVo, response);
            return false;
        }
    }

    private void doResponse(ResultVo resultVo, HttpServletResponse response) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        String s = new ObjectMapper().writeValueAsString(resultVo);
        out.print(s);
        out.flush();
        out.close();
    }
}
